<?php

class Naneau_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    private $_auth;
    private $_acl;

    private $_noauth = array(
    'module' => 'default',
    'controller' => 'user',
    'action' => 'login'
    );

    private $_noacl = array(
    'module' => 'default',
    'controller' => 'error',
    'action' => 'privileges'
    );

    public function __construct($auth, $acl)
    {
        $this->_auth = $auth;
        $this->_acl = $acl;
    }

    /**
     * check if the request can be made, i.e. the user in Auth is allowed
     *
     * @param Zend_Controller_Request_Http $request
     */
    public function dispatchLoopStartup($request)
    {
        if ($this->_auth->hasIdentity()) {
            $role = $this->_auth->getIdentity()->role;
            //rol via user in db
        } else {
            $role = 'guest';
            //default rol is guest
        }

        $controller = $request->controller;
        //the requested controller
        $action = $request->action;
        //the requested action
        $module = $request->module;
        //the requested module...

        $resource = $controller;
        //the resource we will be checking for ( = controller)

        if (!$this->_acl->has($resource)) {
            //unknown resource
            
            $resource = null;
            //null will always fail in Zend_Acl::isAllowed()
        }


        if (!$this->_acl->isAllowed($role, $resource, $action)) {
            //user isn't allowed to access this resource

            if (!$this->_auth->hasIdentity()) {
                //user doesn't even have an identity
                //i.e. not logged in
                $module = $this->_noauth['module'];
                $controller = $this->_noauth['controller'];
                $action = $this->_noauth['action'];
            } else {
                //the user's identity does not have the rights to acces this resource
                $module = $this->_noacl['module'];
                $controller = $this->_noacl['controller'];
                $action = $this->_noacl['action'];
            }
        }
        //aanpassen request

        $request->setModuleName($module);
        $request->setControllerName($controller);
        $request->setActionName($action);
        //redirect of doorlaten
    }
}